package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author mff
 * @date 2022/6/13 9:01
 * @mood happy
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;



    @PostMapping("/submit")
    public R<String> submitOrder(@RequestBody Orders orders){
//        A. 获得当前用户id, 查询当前用户的购物车数据
        Long currentId = BaseContext.getCurrentId(); //userID

//        获得总价
        AtomicInteger amount = new AtomicInteger(0);

//      随机生成的订单id
        long id = IdWorker.getId();

        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
//        B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(currentId);

//        C. 根据userID, 查询地址数据
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId, user.getId());
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook userAddress = addressBookService.getOne(addressBookLambdaQueryWrapper);  //orders.getId()是购物车的id


        if (userAddress==null){
            return R.error("未添加收货地址");
        }
//        D. 组装订单明细数据, 批量保存订单明细
        for (ShoppingCart shoppingCart : list) {
//            设置基本数据
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);

            orderDetail.setOrderId(id);
//            获得单价
            BigDecimal price = shoppingCart.getAmount();
//            获得当前dish的数量
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
//            获得总价
            orderDetail.setAmount(shoppingCart.getAmount());

            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());

            orderDetailService.save(orderDetail);
        }

//        E. 组装订单数据, 批量保存订单数据
        orders.setId(orders.getId());//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(user.getId());//用户id
        orders.setNumber(String.valueOf(id));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(userAddress.getConsignee());//收货人
        orders.setPhone(userAddress.getPhone());//收货人联系电话
        orders.setAddress(
                (userAddress.getProvinceName() == null ? "" : userAddress.getProvinceName())
                        + (userAddress.getCityName() == null ? "" : userAddress.getCityName())
                        + (userAddress.getDistrictName() == null ? "" : userAddress.getDistrictName())
                        + (userAddress.getDetail() == null ? "" : userAddress.getDetail()));//省+市+区域+详细地址
        ordersService.save(orders);
//        F. 删除当前用户的购物车列表数据
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

        return R.success("success");
    }


//    分页查询订单
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> page(int page, int pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        ordersLambdaQueryWrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(ordersPage,ordersLambdaQueryWrapper);

        BeanUtils.copyProperties(ordersPage, ordersDtoPage);

        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);
            String orderId = record.getNumber();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.in(OrderDetail::getOrderId, orderId);
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(list);
            ordersDtos.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }

    // 分页查询后台订单
    @GetMapping("/page")
    public R<Page<Orders>> pagehoutai(int page, int pageSize, Long number, String beginTime,String endTime){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.between(beginTime!=null&&endTime!=null,Orders::getCheckoutTime,beginTime,endTime);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getCheckoutTime);
        ordersLambdaQueryWrapper.eq(number!=null,Orders::getNumber, number);
        Page<Orders> page1 = ordersService.page(ordersPage,ordersLambdaQueryWrapper);
        return R.success(page1);
    }

    @PutMapping
    public R<String> modifyStatus(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> ordersLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        ordersLambdaUpdateWrapper.set(Orders::getStatus, orders.getStatus());
        ordersLambdaUpdateWrapper.eq(Orders::getId, orders.getId());
        ordersService.update(ordersLambdaUpdateWrapper);
        return R.success("状态修改成功");
    }


    @PostMapping("/again")
    public R<String> againOrder(@RequestBody Orders orders){  //order表的id

        Orders userOrder = ordersService.getById(orders.getId());
        String orderId = userOrder.getNumber();  // 订单orderID
        Long userId = userOrder.getUserId();  // 用户userId 1
//        找到菜品
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.in(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailsList = orderDetailService.list(orderDetailLambdaQueryWrapper);
//        循环遍历list中的dishId，并通过dishId找到菜品信息，将菜品加入到购物车中
//        创建一个购物车对象用于回显数据
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailsList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCarts.add(shoppingCart);
        }
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("添加成功");
    }
}
